package kr.pe.asuraho.zhibogo;

import static kr.pe.asuraho.StaticMethods.nvl;
import static kr.pe.asuraho.StaticMethods.crontabCode;

import java.util.Map;

import kr.pe.asuraho.BaseService;
import kr.pe.asuraho.SchedulerJob;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class Setting extends BaseService{
	
	public String form(){
		add("setting", getSqlSession().selectOne("kr.pe.asuraho.selectTorSetting"));
		return "/WEB-INF/jsp/setting.jsp";
	}
	
	public String update(){
		Map<String, Object> old_settingInfo = getSqlSession().selectOne("kr.pe.asuraho.selectTorSetting");
		String old_interval = nvl(old_settingInfo.get("job_interval"));
		String new_interval = nvl(getParamMap().get("interval"));
		
		getSqlSession().update("kr.pe.asuraho.updateTorSetting", getParamMap());
		
		if(!new_interval.equals(old_interval)){
			String interval = crontabCode(new_interval);
			
			try {
				Scheduler sd = StdSchedulerFactory.getDefaultScheduler();
				sd.deleteJob(new JobKey("HibogoJob"));
				
				JobDetail job = JobBuilder.newJob(SchedulerJob.class).withIdentity("HibogoJob").withDescription("스따또~").build();
				
				Trigger trigger = TriggerBuilder.newTrigger().
												 withIdentity("HibogoTrigger").
												 withSchedule(CronScheduleBuilder.cronSchedule(interval)).
												 build();
				
				sd.scheduleJob(job, trigger);
				sd.start();
				
System.out.println("재시작함!");
			} catch (SchedulerException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			
		}
		
		return "setting.do?method=form";
	}
}